﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace System.Web.Mvc.Html
{
    /// <summary>
    /// Generic HTML delegated IDisposable class to use when developing Html.Begin... methods
    /// </summary>
    public class HtmlDisposable : IDisposable
    {
        private readonly Action<HtmlHelper> onClose;
        private readonly HtmlHelper helper;

        public HtmlDisposable(HtmlHelper htmlHelper, Action<HtmlHelper> onCloseAction)
        {
            if (htmlHelper == null) throw new ArgumentNullException("htmlHelper");
            this.onClose = onCloseAction;
            this.helper = htmlHelper;
        }

        public HtmlDisposable(HtmlHelper htmlHelper)
            : this(htmlHelper, null)
        {
        }

        public void Dispose()
        {
            if (onClose != null) onClose(helper);
        }
    }

    public static class HtmlHelperDisposableExtensions
    {
        public static IDisposable BeginDisposable(this HtmlHelper helper, Action<HtmlHelper> onClose)
        {
            return new HtmlDisposable(helper, onClose);
        }

        public static IDisposable BeginDisposable(this HtmlHelper helper)
        {
            return BeginDisposable(helper, null);
        }
    }
}
